package com.start.cloud.robotcore.boot;

import com.start.cloud.robotcore.Constants;
import com.start.cloud.robotcore.properties.RobotClientConfiguration;
import com.start.cloud.robotcore.properties.RobotClientLocalProperties;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.FilterType;
import org.springframework.core.env.CompositePropertySource;
import org.springframework.core.env.MapPropertySource;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by xxu on 2018/4/24.
 */
@SpringBootApplication
@EnableAutoConfiguration
@ComponentScan(basePackages = { "com.start.cloud", "${bee.config.basePackage}" })
public class RobotStarter {


    public static void run(final Object resource, String args[]) {
        System.setProperty("spring.cloud.config.enabled", "false");
        final ConfigurableApplicationContext appContext = SpringApplication.run(resource, args);
        Runtime.getRuntime().addShutdownHook(new Thread() {
            public void run() {
                synchronized (resource) {
                    SpringApplication.exit(appContext);
                    resource.notify();
                }
            }
        });

        synchronized (resource) {
            while (true) {
                try {
                    resource.wait();
                } catch (InterruptedException e) {
                }
            }
        }
    }

    private static void setDefaultSpringBootProperty() {
        Map<String, Object> restProperties = new HashMap<String, Object>();
        CompositePropertySource cp = RobotClientConfiguration.get().getCompositeProperty();
        for (String propertyKey : cp.getPropertyNames()) {
            if (propertyKey.startsWith(Constants.LOG_PREFIX)) {
                System.setProperty(propertyKey, (String) cp.getProperty(propertyKey));
            }
            if (propertyKey.startsWith(Constants.LOG_LEVEL + ".")) {
                restProperties.put(propertyKey.replaceAll(Constants.LOG_LEVEL_REGX, "logging.level"), cp.getProperty(propertyKey));
            }
        }
        MapPropertySource resetSource = new MapPropertySource(RobotClientLocalProperties.DEFAULT_BEECONFIG_NAME + "Reset", restProperties);
        cp.addFirstPropertySource(resetSource);
        System.setProperty(Constants.CONFIG_APPNAME_KEY, RobotClientConfiguration.get().getLocalProperies().getAppName());
    }

    // 注册默认配置文件
    static {
        setDefaultSpringBootProperty();
    }
}
